package org.example.controller;

import org.example.vo.ResultVo;
import org.example.config.CacheUtil;
import org.example.config.LocalUerContext;
import org.example.entity.User;
import org.example.exception.BusinessException;
import org.example.service.UserService;
import org.example.vo.LoginVo;
import org.example.vo.UserDetail;
import org.example.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

@RestController
public class LoginController {

    @Autowired
    public UserService service;

    @PostMapping("/login")
    public ResultVo<String> login(@RequestBody LoginVo loginVo, HttpServletResponse response) {
        ResultVo<String> resultVo = new ResultVo<>();
        User userByAccount = service.findUserByAccount(loginVo.getAccount());
        if (Objects.nonNull(userByAccount) && loginVo.getPassword().equals(userByAccount.getPassword())) {
            String token = UUID.randomUUID().toString();
            // 3. 写入 Cookie（HttpOnly）
            ResponseCookie cookie = ResponseCookie.from("login_token", token)
                    .httpOnly(true)
                    .secure(false) // 如果是 HTTPS 则改为 true
                    .path("/")
                    .maxAge(30 * 60) // 30分钟
                    .sameSite("Strict")
                    .build();
            // 4. 添加到响应头
            response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
            CacheUtil.getCache().put(token, String.valueOf(userByAccount.getId()));
            CacheUtil.getCache().put(String.valueOf(userByAccount.getId()), token);
            return resultVo.success(token);
        }
        throw new BusinessException(403, "账号密码错误");
    }

    @GetMapping("/get-user")
    public ResultVo<UserDetail> userInfo() {
        ResultVo<UserDetail> resultVo = new ResultVo<>();
        return resultVo.success(service.findUserById(Long.parseLong(LocalUerContext.getUserId())));
    }

    @PostMapping("/logout")
    public ResultVo<Void> logout() {
        String token = CacheUtil.getCache().asMap().get(LocalUerContext.getUserId());
        CacheUtil.getCache().asMap().remove(token);
        CacheUtil.getCache().asMap().remove(LocalUerContext.getUserId());
        return new ResultVo<>();
    }

    @PostMapping("/edit-user")
    public ResultVo<Void> editUser(@RequestBody UserVo userVo) {
        service.editUser(userVo);
        return new ResultVo<Void>().voidSuccess();
    }

    @PostMapping("/add-user")
    public ResultVo<Void> addUser(@RequestBody UserVo userVo) {
        service.addUser(userVo);
        return new ResultVo<Void>().voidSuccess();
    }
}
